package com.weiiew.backend.utils;

import com.weiiew.backend.entity.ScriptFile;
import com.weiiew.backend.operationUtils.OperationSequence;
import lombok.extern.slf4j.Slf4j;

import java.io.EOFException;
import java.io.IOException;
import java.io.InvalidClassException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;


/**
 * @Description 负责管理脚本相关内容
 * @Author 魏锴
 * @Date 2025/4/29
 */

@Slf4j
public class ScriptManager {
    private final Path scriptDirectory;


    public ScriptManager(Path scriptDirectory) throws IOException {
        this.scriptDirectory = scriptDirectory;
        Files.createDirectories(this.scriptDirectory);
        log.info("脚本存储目录初始化完成：" + scriptDirectory);
    }

    // 获取所有脚本列表
    public List<ScriptFile> listScripts() throws IOException {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(scriptDirectory, "*.ser")) {
            return StreamSupport.stream(stream.spliterator(), false)
                    .map(p -> {
                        try {
                            ScriptFile scriptFile = OperationSequence.readMetadata(p);
                            scriptFile.setPath(p.toString());
                            return scriptFile;
                        } catch (InvalidClassException e) {
                            log.warn("文件版本不兼容: {}", p);
                        } catch (EOFException e) {
                            log.warn("文件已损坏: {}", p);
                            e.getStackTrace();
                        } catch (Exception e) {
                            log.error("读取元数据失败: {} ({})", p, e.getClass().getSimpleName());
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
    }
    // 保存脚本（新增或覆盖）
    public void saveScript(String scriptName, OperationSequence sequence) throws IOException {
        validateScriptName(scriptName);
        Path scriptPath = getScriptPath(scriptName);
        sequence.saveToFile(scriptPath);
    }

    // 读取脚本
    public OperationSequence loadScript(String path) throws IOException {
        Path scriptPath = Paths.get(path);
        return OperationSequence.loadFromFile(scriptPath.toString());
    }

    // 删除脚本
    public boolean deleteScript(String path) throws IOException {
        Path scriptPath = Paths.get(path);
        return Files.deleteIfExists(scriptPath);
    }

    // 检查脚本是否存在
    public boolean scriptExists(String scriptName) {
        validateScriptName(scriptName);
        return Files.exists(getScriptPath(scriptName));
    }

    // 获取脚本存储目录路径
    public String getScriptDirectory() {
        return scriptDirectory.toString();
    }

    // 私有工具方法：验证脚本名称合法性
    private void validateScriptName(String scriptName) {
        if (scriptName == null || scriptName.trim().isEmpty()) {
            throw new IllegalArgumentException("脚本名称不能为空");
        }
        if (scriptName.contains("..") || scriptName.contains("/") || scriptName.contains("\\")) {
            throw new IllegalArgumentException("非法的脚本名称");
        }
    }

    // 私有工具方法：获取完整脚本路径
    private Path getScriptPath(String scriptName) {
        return scriptDirectory.resolve(scriptName + ".ser");
    }
}
